import { createSlice, PayloadAction } from "@reduxjs/toolkit"
import { RootState } from "./index"

type InitialState = IState["userInfo"]

const initialState: InitialState = {
  user: {},
  token: ""
}

export const userInfoReducer = createSlice({
  name: "userInfo",
  initialState,
  reducers: {
    setUserInfo: (state, action: PayloadAction<InitialState>) => {
      sessionStorage.setItem("token", action.payload.token)
      return {
        ...state,
        ...action.payload
      }
    },
    logout: (state) => {
      sessionStorage.clear()
      return {
        ...state,
        user: {},
        token: ""
      }
    }
  }
})

export const { setUserInfo, logout } = userInfoReducer.actions

export const userInfoSelector = (state: RootState) => state.userInfo
